package com.njchy.statistics.config;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.context.properties.ConfigurationPropertiesBinding;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.RejectedExecutionHandler;

@Configuration
// 显式启用配置实体类，确保配置参数被绑定
@EnableConfigurationProperties(PointMatchThreadPoolProperties.class)
public class ThreadPoolConfig {

    // 1. 手动注册转换器：用 @ConfigurationPropertiesBinding 注解，强制Spring使用该转换器
    @Bean
    @ConfigurationPropertiesBinding
    public Converter<String, RejectedExecutionHandler> rejectedExecutionHandlerConverter() {
        return new RejectedExecutionHandlerConverter(); // 返回自定义转换器实例
    }

    // 2. 创建线程池Bean：注入配置实体类，直接使用转换后的拒绝策略
    @Bean
    public ThreadPoolTaskExecutor pointMatchExecutor(PointMatchThreadPoolProperties poolProperties) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        // 设置线程池参数（全部从配置实体类获取，无硬编码）
        executor.setCorePoolSize(poolProperties.getCorePoolSize());
        executor.setMaxPoolSize(poolProperties.getMaxPoolSize());
        executor.setQueueCapacity(poolProperties.getQueueCapacity());
        executor.setKeepAliveSeconds(poolProperties.getKeepAliveSeconds());
        executor.setThreadNamePrefix(poolProperties.getThreadNamePrefix());

        // 关键：直接使用配置实体类中已转换好的 RejectedExecutionHandler 实例
        RejectedExecutionHandler rejectedHandler = poolProperties.getRejectedExecutionHandler();
        executor.setRejectedExecutionHandler(rejectedHandler);

        executor.initialize();
        return executor;
    }
}